package com.xiaoming.mojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeRequest;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeResponse;
import com.xiaoming.mojcodesandbox.model.ExecuteMessage;
import com.xiaoming.mojcodesandbox.model.JudgeInfo;
import com.xiaoming.mojcodesandbox.utils.ProcessUtils;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class JavaDockerCodeSandboxOld implements CodeSandBox{
    public static void main(String[] args) {
        JavaDockerCodeSandboxOld javaCodeSandbox = new JavaDockerCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        String code = ResourceUtil.readStr("testCode.simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        executeCodeRequest.setLanguage("java");
        executeCodeRequest.setCode(code);
        ExecuteCodeResponse executeCodeResponse = javaCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }


    private static final long TIME_OUT=5000L;
    private static final String GLOBAL_CODE_DIR_NAME="tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME="Main.java";
    private static boolean FIRST_INIT=true;


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        //根目录
        String userDir=System.getProperty("user.dir");
        //代码包目录
        String globalCodePathName=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;

        if(!FileUtil.exist(globalCodePathName))
        {
            FileUtil.mkdir(globalCodePathName);
        }


        //1.把用户代码隔离存放
        String  userCodeParentPath=globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        File file = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2.编译代码 得到class文件
        String compileCmd=String.format("javac -encoding utf-8 %s",file.getAbsoluteFile());
        try {
            Process process=Runtime.getRuntime().exec(compileCmd);
            String operationName="编译";
            ExecuteMessage executeMessage= ProcessUtils.runProcessAndGetMessage(process,operationName);
            System.out.println(executeMessage);
        }
        catch (Exception e) {
            return getErrorResponse(e);
        }

        //3.创建容器 把编译后文件上传到容器
        //创建默认docker Client
        DockerClient dockerClient= DockerClientBuilder.getInstance().build();
        //拉取镜像
        String image="openjdk:8-alpine";
        if(FIRST_INIT)
        {
            PullImageCmd pullImageCmd=dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback=new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像");
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }

        }
        FIRST_INIT=false;

        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig=new HostConfig();
        //挂载文件
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        //内存限制 100M
        hostConfig.withMemory(100*1000*1000L);
        //限制cpu
        hostConfig.withCpuCount(1L);

        CreateContainerResponse createContainerResponse = containerCmd
                //禁用网络
                .withNetworkDisabled(true)
                //禁止向root目录写文件
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .withHostConfig(hostConfig)
                .exec();
        System.out.println(createContainerResponse);
        System.out.println("创建容器成功");
        String containId=createContainerResponse.getId();

        //启动容器
        StartContainerCmd startContainerCmd = dockerClient.startContainerCmd(containId);
        startContainerCmd.exec();

        //执行命令并获取结果
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        for (String inputStr : inputList) {
            StopWatch stopWatch=new StopWatch();
            String[] inputArray= inputStr.split(" ");
            String[] cmdArray=ArrayUtil.append(new String[]{"java","-cp","/app","Main"},inputArray);

            //创建命令
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdout(true)
                    .withAttachStdin(true)
                    .exec();
            System.out.println("创建执行命令:"+execCreateCmdResponse);
            String id = execCreateCmdResponse.getId();
            //收集运行结果信息
            ExecuteMessage executeMessage=new ExecuteMessage();
            final String[] errMessage = {null};
            final String[] message = {null};
            long time=0;
            final boolean[] timeout = {true};
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    //执行完成 则没有超时
                    timeout[0] =false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    if(frame.getStreamType().equals(StreamType.STDERR))
                    {
                        errMessage[0] =new String(frame.getPayload());
                        System.out.println("输出错误结果" + new String(frame.getPayload()));
                    }
                    else {
                        message[0] =new String(frame.getPayload());
                        System.out.println("结果" + new String(frame.getPayload()));
                    }
                    super.onNext(frame);
                }
            };
            final long[] maxMemory={0L};
            //获取内存占用
            StatsCmd statsCmd = dockerClient.statsCmd(containId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());

                }

                @Override
                public void onStart(Closeable closeable) {

                }


                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);

            try {
                //执行命令
                stopWatch.start();
                dockerClient.execStartCmd(id)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                //Thread.sleep(10000L);
                stopWatch.stop();
                //执行时间
                time=stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setErrorMessage(errMessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }

        //4.整理输出
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        List<String> outputList =new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage=executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage))
            {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());

        }
        //TODO
        Optional<Long> first = executeMessageList.stream().map(ExecuteMessage::getTime).sorted((t1,t2)-> Math.toIntExact(t2 - t1)).findFirst();
        Long time = null;
        if(!first.isPresent())
        {
            time=first.get();
        }
        JudgeInfo judgeInfo=new JudgeInfo();
        //judgeInfo.setMemory();
        judgeInfo.setTime(time);

        if(outputList.size()==executeMessageList.size())
        {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setJudgeInfo(judgeInfo);
        executeCodeResponse.setOutPutList(outputList);

        return executeCodeResponse;


    }




    //6错误处理 提升健壮性

    public ExecuteCodeResponse getErrorResponse(Throwable e)
    {
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        executeCodeResponse.setOutPutList(new ArrayList<>());
        return executeCodeResponse;

    }
}
